<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from "vue";
import { onLoad, onPageScroll, onShareAppMessage } from "@dcloudio/uni-app";
import { getDetail, applyActivity, getShareInfo, getIsCollect, updateCollectStatus, type ActivityInfo } from "@/api/activity";
import { getUserDetail } from "@/api/user";
import { useAccountStore } from "@/stores/account";
import { checkLogin, getImageLocalPath, handleToPage } from "@/utils";

const accountStore = useAccountStore();

const info = reactive<ActivityInfo>({
  id: 0,
  price: '0.00',
  active_status: 2,
  num: 0,
  title: '',
  desc: '',
  content: '',
  apply: []
});

const tabs = ['活动详情', '已报名嘉宾'];
const activeTabItem = ref(0);

/************** 收藏 *************/
const isCollect = ref(false);
/** 处理收藏状态 */
async function handleCollect () {
  if(!checkLogin()) return;
  const { status } = await updateCollectStatus({id: info.id});
  uni.showToast({ title: `${status ? '收藏' : '取消'}成功` });
  isCollect.value = status;
}

/************** 报名 *************/
const popupVisible = ref(false);
const actionId = ref(0);
const profile = reactive<Record<string, any>>({
  realname: '',
  phone: '',
  company_name: '',
  position: '',
  email: '',
  share_uid: undefined
});
async function handleOpenPopup(id:number) {
  const data = await getUserDetail();
  Object.assign(profile, data);
  actionId.value = id;
  popupVisible.value = true;
}

const share_uid = ref('');
async function handleApplyActivity(){
  const requiredFields = ['realname', 'phone', 'company_name', 'position'] as const;
  const hasEmptyField = requiredFields.some(field => !profile[field]?.trim());
  if (hasEmptyField) {
    uni.showToast({ title: '请先更新信息', icon: 'none' });
    return;
  }

  // 如存在分享来源，更新报名信息
  const { shareInfo } = useAccountStore();
  if(share_uid.value) {
    profile.share_uid = share_uid.value;
  } else if(shareInfo.id == info.id) {
    profile.share_uid = shareInfo.uid;
  }

  await applyActivity(profile);
  uni.showToast({ title: '提交成功' });
  uni.redirectTo({ url: '/pages/user/activity' });
}

onLoad(async (options)=>{
  // 记录分享来源用户ID
  if(options?.uid) share_uid.value = options.uid;
  
  if(options?.id){
    const data = await getDetail({id: options.id});
    Object.assign(info, data);

    // 查询收藏状态
    if(accountStore.hasLogin) {
      const { status } = await getIsCollect({id: options.id});
      isCollect.value = status;
    }
  }
});

/************** 分享 *************/
async function handleShare() {
  if(!checkLogin()) return;
  const data = await getShareInfo({id: info.id});
  createSharePoster(data);
}

/** 生成分享海报 */
async function createSharePoster({ title, log, share_img, share_code } :any){
  uni.showLoading({ title:'正在生成海报...' });
  const instance = getCurrentInstance();

  const ctx = uni.createCanvasContext('myCanvas', instance);
  // 填充一个与画布动态宽高相等的矩形
  ctx.setFillStyle('white');
  ctx.fillRect(0, 0, 375, 500);
  try {
    // logo
    const login = await getImageLocalPath(log);
    ctx.drawImage(login, 24, 24, 123, 34);

    // 活动封面
    const cover = await getImageLocalPath(`https://api.minglvtang.com${share_img}`);
    ctx.drawImage(cover, 12, 72, 350, 200);

    // 小程序码
    const mpCode = await getImageLocalPath(share_code);
    ctx.drawImage(mpCode, 138, 324, 100, 100);
  } catch (error) {
    console.error(error)
  }
  ctx.fillStyle = "#000";
  ctx.font = "14px Arial";
  ctx.fillText(title, 16, 300, 330);

  ctx.font = "12px Arial";
  const text = "长按识别二维码参与活动";
  const textWidth = ctx.measureText(text).width;
  const textX = (375 - textWidth) / 2;
  ctx.fillText(text, textX, 450);
  
  ctx.draw(false, ()=>{
    uni.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: ({tempFilePath}) => {
        uni.hideLoading();
        // 在H5平台下，tempFilePath 为 base64
        // #ifdef MP-WEIXIN
        uni.showShareImageMenu({
          path: tempFilePath,
          fail: err => {
            console.log("fail:", err);
          }
        })
        // #endif
      }
    });
  });
}

onShareAppMessage(()=>{
  const { userInfo } = useAccountStore();
  return {
    title: info.title,
    path: `/pages/activity/detail?id=${info.id}&uid=${userInfo.id}`,
    imageUrl: `https://api.minglvtang.com${info.imgs}`
  }
});

// 吸顶变色
const isScrolled = ref(false);
onPageScroll((e)=>{
  isScrolled.value = e.scrollTop > 0;
});
</script>

<template>
  <view class="relative overflow-hidden">
    <page-navbar title="活动详情" bgColor="#ffffff" :isScrolled="isScrolled"></page-navbar>

    <image class="w-full h-52 align-middle" :src="`https://api.minglvtang.com${info.imgs}`" mode="widthFix" />

    <view class="relative px-4 py-5 grid gap-3 bg-white grid-cols-5">
      
      <view class="size-10 flex items-center justify-around bg-white shadow-xl shadow-black/9 rounded-full absolute -top-5 right-18" @click="handleShare">
        <view class="i-material-symbols-share text-#1373FF"></view>
      </view>

      <view class="size-10 flex items-center justify-around bg-white shadow-xl shadow-black/9 rounded-full absolute -top-5 right-4" @click="handleCollect">
        <view :class="`i-solar-star-bold ${isCollect ? 'text-#FBCD38' : 'text-black/60'}`"></view>
      </view>
      
      <view class="text-(2xl #333333) font-500 truncate col-span-5">{{info.title}}</view>
      <view class="text-(sm #333333) line-clamp-2 col-span-5">{{info.desc}}</view>
      <view class="col-span-3 border-r-(~ solid #D8D8D8) mr-3">
        <view class="text-(sm #999999) mb-2">时间</view>
        <view class="text-(sm #333333)">{{info.start_time}}</view>
        <view class="text-(sm #333333)">{{info.end_time}}</view>
      </view>
      <view class="col-span-2">
        <view class="text-(sm #999999) mb-2">地点</view>
        <view class="text-(sm #333333) font-500">{{info.province}}  {{info.city}}  {{info.zone}}</view>
      </view>
    </view>

    <view class="mt-3 mx-4 mb-10 pt-1.5 shadow-2xl shadow-[#1373FF]/8 rounded-lg bg-#5199F9">
      <view class="flex">
        <view class="font-500 flex-1 text-(lg center) bg-white rounded-t-md" @click="activeTabItem=0">
          <view 
            class="px-3 py-2"
            :class="[activeTabItem== 0 ? 'text-black bg-white rounded-t-md' : 'bg-gradient-to-b from-#5199F9 to-#0164E6 rounded-br-md text-white']"
          >活动详情</view>
        </view>
        <view class="font-500 flex-1 text-(lg center) bg-white rounded-t-md" @click="activeTabItem=1">
          <view 
            class="px-3 py-2"
            :class="[activeTabItem== 1 ? 'text-black bg-white rounded-t-md' : 'bg-gradient-to-b from-#5199F9 to-#0164E6 rounded-bl-md text-white']"
          >已报名嘉宾</view>
        </view>
      </view>

      <view class="p-3 bg-white rounded-b-lg grid gap-3" v-show="activeTabItem == 0">
        <view class="text-(sm #333333)">
          <rich-text :nodes="info.content"></rich-text>
        </view>
      </view>
<!--  
      <view class="p-3 bg-white rounded-b-lg grid gap-3" v-show="activeTabItem == 1">
        <view class="flex items-center justify-between p-2 rounded-md bg-gradient-to-br from-#EDF4FF to-#EDF4FF/30">
          <view class="text-(sm #333333) font-400">15:00-15:15</view>
          <view class="text-(sm #333333) font-500">签到</view>
        </view>
        <view class="flex items-center justify-between p-2 rounded-md bg-gradient-to-br from-#EDF4FF to-#EDF4FF/30">
          <view class="text-(sm #333333) font-400">15:15-15:45</view>
          <view class="text-(sm #333333) font-500">自我介绍，破冰</view>
        </view>
        <view class="flex items-center justify-between p-2 rounded-md bg-gradient-to-br from-#EDF4FF to-#EDF4FF/30">
          <view class="text-(sm #333333) font-400">15:45-17:15</view>
          <view class="text-(sm #333333) font-500">主题分享</view>
        </view>
        <view class="flex items-center justify-between p-2 rounded-md bg-gradient-to-br from-#EDF4FF to-#EDF4FF/30">
          <view class="text-(sm #333333) font-400">17:15-17:35</view>
          <view class="text-(sm #333333) font-500">自由交流</view>
        </view>
        <view class="flex items-center justify-between p-2 rounded-md bg-gradient-to-br from-#EDF4FF to-#EDF4FF/30">
          <view class="text-(sm #333333) font-400">17:35</view>
          <view class="text-(sm #333333) font-500">活动结束</view>
        </view>
      </view>
-->
      <view class="p-3 bg-white rounded-b-lg grid gap-3" v-show="activeTabItem == 1">
        <view class="text-(sm #999999)">规模：{{info.num}}人 | 已报名：{{info.apply.length}}人</view>
        <view class="max-h-40 overflow-y-auto grid gap-3">
          <view class="grid grid-cols-[auto_1fr] items-center" v-for="item in info.apply" :key=item.id>
            <image class="size-11 rounded-full row-span-2 mr-2" :src="item.user.avatar || 'https://static.minglvtang.com/images/avatar_empty.jpeg'" mode="aspectFit" />
            <view class="text-(sm #333333)">{{item.forms.company_name}}</view>
            <view class="text-(xs #999999)">{{item.forms.position}}</view>
          </view>
        </view>
      </view>
    </view>

    <view class="h-12">
      <view class="bg-#253851 w-86 fixed bottom-5 left-50% -translate-x-50% z-10 rounded-lg overflow-hidden flex items-center">
        <view class="flex-1 px-4">
          <view class="text-white flex items-end" v-if="info.price > 0">
            <view class="text-sm">¥</view>
            <view class="ml-1 text-xl/6">{{info.price}}</view>
          </view>
          <view class="text-(xl white)" v-else>免费</view>
          <view class="text-(xs #93989E)">席位有限，先到先得！</view>
        </view>
        <view v-if="info.active_status == 2" class="bg-([url(https://static.minglvtang.com/images/bg_entry.png)] contain no-repeat center) w-37 h-12 flex items-center justify-around text-(lg white) opacity-50"> 已结束 </view>
        <view 
          v-else 
          class="bg-([url(https://static.minglvtang.com/images/bg_entry.png)] contain no-repeat center) w-37 h-12 flex items-center justify-around text-(lg white)"
          @click="handleOpenPopup"
        >
          立即报名
        </view>
      </view>
    </view>
    
    <view class="fixed inset-0 z-50 bg-black/60 w-screen h-screen" v-show="popupVisible">
      <view class="absolute left-50% -translate-x-50% w-86 rounded-b-2xl bottom-3 mb-[--safe-area-inset-bottom] page-popup">
        <view class="text-(base #333333) font-500 px-5">您将用以下身份参与本次活动</view>
        <view class="px-5 pb-5 mt-3 bg-gradient-to-b from-white/0 from-10% to-white">
          <view class="text-(base #333333) grid gap-1">
            <view>姓名：{{profile.realname || '暂无信息'}}</view>
            <view>手机号：{{profile.phone || '暂无信息'}}</view>
            <view>企业：{{profile.company_name || '暂无信息'}}</view>
            <view>职位：{{profile.position || '暂无信息'}}</view>
            <view>邮箱：{{profile.email || '暂无信息'}}</view>
          </view>
          <view class="mt-5 grid grid-cols-3 gap-3">
            <uv-button
              type="primary"
              size="large"
              text="更新信息"
              :custom-style="{
                fontSize: '18px',
                backgroundImage: 'linear-gradient(to right, #5199F9, #0164E6)',
                height: '48px',
                borderRadius: '8px',
                borderColor: 'transparent'
              }"
              @click="handleToPage(`/pages/user/profile`)"
            ></uv-button>
            <uv-button
              type="primary"
              size="large"
              text="确认报名"
              :custom-style="{
                fontSize: '18px',
                backgroundImage: 'linear-gradient(to right, #5199F9, #0164E6)',
                height: '48px',
                borderRadius: '8px',
                borderColor: 'transparent'
              }"
              @click="handleApplyActivity"
            ></uv-button>
            <uv-button
              size="large"
              text="取消"
              :custom-style="{
                fontSize: '18px',
                height: '48px',
                borderRadius: '8px',
                borderColor: '#D8D8D8'
              }"
              @click="popupVisible = false"
            ></uv-button>
          </view>
        </view>
      </view>
    </view>

    <canvas canvas-id="myCanvas" id="myCanvas" class="w-[375px] h-[500px] fixed z-0 opacity-0"></canvas>

  </view>
</template>
